<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Microsoft YaHei:300,300italic,400,400italic,700,700italic|Inziu Iosevka Slab SC:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="原文标题：AnIntuitive Introduction to Generative Adversarial Networks作者：KeshavDhandhania、ArashDelijani翻译：申利彬校对：和中华  本文的概要：  简单回顾深度学习 图像生成问题 生成任务中的关键问题 生成对抗网络 挑战 进一步阅读 总结">
<meta property="og:type" content="article">
<meta property="og:title" content="一文读懂生成对抗网络 GANs">
<meta property="og:url" content="http://idmk.oschina.io/2018/02/11/YWDDSCDKWLGAN/index.html">
<meta property="og:site_name" content="苦舟">
<meta property="og:description" content="原文标题：AnIntuitive Introduction to Generative Adversarial Networks作者：KeshavDhandhania、ArashDelijani翻译：申利彬校对：和中华  本文的概要：  简单回顾深度学习 图像生成问题 生成任务中的关键问题 生成对抗网络 挑战 进一步阅读 总结">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://idmk.oschina.io/2018/02/11/YWDDSCDKWLGAN/markdown-img-paste-20180211220853900.png">
<meta property="og:image" content="http://idmk.oschina.io/2018/02/11/YWDDSCDKWLGAN/markdown-img-paste-20180211221455361.png">
<meta property="og:updated_time" content="2018-02-11T14:03:16.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="一文读懂生成对抗网络 GANs">
<meta name="twitter:description" content="原文标题：AnIntuitive Introduction to Generative Adversarial Networks作者：KeshavDhandhania、ArashDelijani翻译：申利彬校对：和中华  本文的概要：  简单回顾深度学习 图像生成问题 生成任务中的关键问题 生成对抗网络 挑战 进一步阅读 总结">
<meta name="twitter:image" content="http://idmk.oschina.io/2018/02/11/YWDDSCDKWLGAN/markdown-img-paste-20180211220853900.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://idmk.oschina.io/2018/02/11/YWDDSCDKWLGAN/"/>





  <title>一文读懂生成对抗网络 GANs | 苦舟</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">苦舟</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">学海无涯，吾将上下求索。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://idmk.oschina.io/2018/02/11/YWDDSCDKWLGAN/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="东木金">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苦舟">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">一文读懂生成对抗网络 GANs</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-02-11T22:03:16+08:00">
                2018-02-11
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>原文标题：AnIntuitive Introduction to Generative Adversarial Networks<br>作者：KeshavDhandhania、ArashDelijani<br>翻译：申利彬<br>校对：和中华</p>
</blockquote>
<p>本文的概要：</p>
<ul>
<li>简单回顾深度学习</li>
<li>图像生成问题</li>
<li>生成任务中的关键问题</li>
<li>生成对抗网络</li>
<li>挑战</li>
<li>进一步阅读</li>
<li>总结<a id="more"></a>
</li>
</ul>
<h2 id="图像生成问题"><a href="#图像生成问题" class="headerlink" title="图像生成问题"></a>图像生成问题</h2><p>图像生成问题上，我们希望机器学习模型可以生成图像。为了训练模型，我们得到了一个图像数据集（比如从网络下载的 1,000,000 张图片）。在测试的时候，模型可以生成图像，这些图像看起来像属于训练集，但实际上并不是训练集中的图像。也就是说，我们想生成新的图像（与单纯地记忆相反），但仍然希望它能捕获训练数据集中的模式，从而使新的图像感觉与训练数据集相似。</p>
<img src="/2018/02/11/YWDDSCDKWLGAN/markdown-img-paste-20180211220853900.png" alt="图像生成问题：没有输入，所需的输出是一个图像" title="图像生成问题：没有输入，所需的输出是一个图像">
<p>需要注意的一点是：在测试或预测阶段，这个问题没有输入。每次“运行模型”时，我们希望它生成（输出）一个新的图像。这可以说输入将从一个容易抽样的分布（例如均匀分布或高斯分布）中随机抽样而来。</p>
<h2 id="生成任务中的关键问题"><a href="#生成任务中的关键问题" class="headerlink" title="生成任务中的关键问题"></a>生成任务中的关键问题</h2><p>生成任务中的关键问题是：什么是一个好的损失函数？假如你有两张机器学习模型生成的图片，我们如何决定哪一个更好，好多少呢？</p>
<p>在以前的方法中，这个问题最常见的解决方案是计算输出图像和训练集中最邻近图像的距离，其中使用一些预定义的距离度量标准来计算距离。例如，在语言翻译任务中，我们通常有一个源语句和一个小的（约 5 个）目标句子集，也就是由不同翻译人员提供的译文。当模型生成一个译文，我们把译文与提供的目标句子比较，然后根据它距离哪个目标句子最近，分配一个相应的分数（特别是，我们是用 BLEU 分数，它是根据两个句子之间有多少个 n-grams 匹配的距离度量标准）。但这是一种单句子翻译方法，当目标是一个较大的文本时，同样的方法会使损失函数的质量严重恶化。例如，我们的任务可能是生成给定文章的段落摘要，那么这种恶化源于少量的样本无法代表在所有可能的正确答案中观察到的变化范围。</p>
<h2 id="生成对抗网络"><a href="#生成对抗网络" class="headerlink" title="生成对抗网络"></a>生成对抗网络</h2><p>GAN 针对上面问题的回答是：用另外一个神经网络 — 记分神经网络（称为判别器 Discriminator），它将评估生成神经网络输出的图像的真实性。这两个神经网络具有相反的目标（对抗），生成网络的目标是生成一个看起来真实的假图像，判别网络的目标是区分假图像和真实图像。</p>
<p>这将生成任务的设置类似于强化学习的双人游戏（如象棋，Atari games or 围棋），在强化学习中我们有一个从零开始通过自我对抗不断改进的机器学习模型 。象棋或者围棋这些游戏的对抗双方总是对称的（尽管并非总是如此），但对于 GAN 的设置，两个网络的目标和角色是不相同的。一个网络产生假的样本，而另一个网络区分真的和假的样本。<br><img src="/2018/02/11/YWDDSCDKWLGAN/markdown-img-paste-20180211221455361.png" alt="生成对抗网络的示意图，生成器网络标记为 G，判别器网络标记为 D" title="生成对抗网络的示意图，生成器网络标记为 G，判别器网络标记为 D"></p>
<p>如上图所示，是生成对抗网络示意图。生成网络 G 和判别网络 D 在进行一场双方极大极小博弈。首先，为了更好地理解这种对抗机制，需要注意到判别网络（D）的输入可以是从训练集中抽样出的样本，也可以是生成网络（G）的输出，不过一般是 50% 来自训练集，剩余 50% 来自 G。为了从 G 中生成样本，我们从高斯分布中提取潜在的向量并输入生成网络（G）。如果我们想生成 200*200 的灰度图像，那么生成网络（G）的输出应该是 200*200 的向量。下面给出目标函数，它是判别网络（D）做预测的标准对数似然函数。</p>
<p>生成网络（G）是最小化目标函数，也就是减小对数似然函数或是说“迷惑”判别网络（D）。也就是说，无论何时从生成网络（G）输出中抽取样本作为判别网络（D）的输入，都希望判别网络识别为真样本。判别网络（D）是要最大化目标函数，也就是要增大对数似然函数或者说是把真实样本和生成样本区分开。换句话说，如果生成网络（G）在“迷惑”判别网络（D）上效果很好，也就会通过增大公式第二项中 D(G(z)) 来最小化目标函数。另外，如果判别网络（D）能很好地工作，那么在从训练数据中选择样本的情况下，会通过第一项（因为 D(x) 很大）增大目标函数，也会通过第二项减小它（因为 D(x) 很小）。</p>
<p>如同平常的训练过程一样，使用随机初始化和反向传播，此外，我们需要单独交替迭代更新生成器和判别器。下面是在特定问题上应用 GANs 的端到端的工作流程描述：</p>
<ol>
<li>决定 GAN 网络架构：G 的架构是什么？ D 的架构是什么？</li>
<li>训练：一定数量的交替更新<ul>
<li>更新 D（固定 G）：一半样本是真的，另一半是假的</li>
<li>更新 G（固定 D）：生成所有样本（注意，即使 D 保持不变，梯度流还是会经过 D）</li>
</ul>
</li>
<li>人工检查一些假样本，如果质量很高（或者质量没有提升）则停止，否则重复 2。</li>
</ol>
<h2 id="挑战"><a href="#挑战" class="headerlink" title="挑战"></a>挑战</h2><p>训练 GANs 最关键的挑战是有可能不收敛，有时这个问题也被称为模式崩溃（mode collapse）。举个例子，来简单解释这个问题。假设任务是生成数字图像，就像 MNIST 数据集中的一样。可能出现的问题（实践中确实出现）是生成器 G 开始生成数字 6，而不能生成其它数字。一旦 D 适应 G 的当前行为，为了最大限度地提高分类的准确性，它开始把所有的数字 6 归为假，所有其它数字都是真实的（假设它不能分辨假的 6 和真实的 6）。然后 G 又适应了 D 的当前行为，开始只生成数字 8 而不生成其它数字。然后 D 又适应，开始把数字 8 归为假，其它的都是真。接着 G 又开始只生成 3，如此循环下去。基本上，生成器 G 仅生成与训练数据集的一个小的子集相似的图像，而一旦识别器 D 开始把这个小的子集与其余的区分开，生成器 G 又转换到另外的子集，它们将一直简单的来回震荡。虽然这个问题没有被完全解决，但还是有一些方法可以避免这个问题。这些方法涉及小批量特征（minibatch features）和多次更新 D 的反向传播。我们不再讨论这些方法的细节，如果要了解更多信息，请查看下一节中的建议阅读材料。</p>
<h2 id="进一步阅读"><a href="#进一步阅读" class="headerlink" title="进一步阅读"></a>进一步阅读</h2><p>如果你想更深一步了解 GANs，我建议你阅读 ICCV 2017 tutorials on GANs（ <a href="https://sites.google.com/view/iccv-2017-gans/home），那里有很多最新的教程，并且它们对" target="_blank" rel="external">https://sites.google.com/view/iccv-2017-gans/home），那里有很多最新的教程，并且它们对</a> GANs 的不同方面各有侧重。</p>
<p>我还想说一点关于条件 GANs（Conditional GANs）的概念，条件 GANs，是在输入的条件下产生输出。例如，任务可能是输出与输入描述相匹配的图像。所以，当你输入狗时，输出的应该是狗的图像。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/11/Book-List-about-ECG/" rel="next" title="Book List About ECG">
                <i class="fa fa-chevron-left"></i> Book List About ECG
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/02/11/Pattern-Recognition/" rel="prev" title="Pattern Recognition">
                Pattern Recognition <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="东木金" />
          <p class="site-author-name" itemprop="name">东木金</p>
           
              <p class="site-description motion-element" itemprop="description">正在学习机器学习，希望能变得很强！</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">162</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">42</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/bdmk" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:catcherchan94@outlook.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#图像生成问题"><span class="nav-number">1.</span> <span class="nav-text">图像生成问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生成任务中的关键问题"><span class="nav-number">2.</span> <span class="nav-text">生成任务中的关键问题</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#生成对抗网络"><span class="nav-number">3.</span> <span class="nav-text">生成对抗网络</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#挑战"><span class="nav-number">4.</span> <span class="nav-text">挑战</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#进一步阅读"><span class="nav-number">5.</span> <span class="nav-text">进一步阅读</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">东木金</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
